package com.bluebench.bigul.service.processor;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import com.bluebench.bigul.domain.Element;
import com.bluebench.bigul.domain.Element.Attribute;
import com.bluebench.bigul.domain.Invocation;
import com.bluebench.bigul.domain.Tag;
import com.bluebench.bigul.domain.graphics.Graphic;
import com.bluebench.bigul.exception.GraphicInitializationException;
import com.bluebench.bigul.service.DocumentGenerator;

public class ElementProcessor extends GenericProcessor{
	
	private Tag tag;
	
	@Override
	public Object process() throws SecurityException, IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException, GraphicInitializationException {

		
		Element element = (Element)tag;
		
		Object itextObj=null;		
		Invocation invocation = element.getInvocation();
		if(invocation!=null){
			itextObj = element.getInvocation().invoke();
			if(itextObj instanceof Graphic){
				DocumentGenerator.getWriter().getDirectContent().saveState();
			}			
		}				
		List<Attribute> attributes = element.getAttributes();
		for(Attribute a : attributes){
			AttributeProcessor aProcessor=null;
			try {
				aProcessor = (AttributeProcessor)GenericProcessor.getInstance(ATTRIBUTE_PROCESSOR);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			aProcessor.set(itextObj);
			a.setProcessor(aProcessor);
			a.process();
		}
		
		if(itextObj instanceof Graphic){
			DocumentGenerator.getWriter().getDirectContent().restoreState();
		}
		
		return itextObj;
	}

	@Override
	public void set(Tag t) {
		
		tag = t;
	}

}
